<template>
  <el-form :model="form" @submit="submit" ref="form" v-loading="loading">
    <el-form-item prop="name" label="资源名称">
      <el-input v-model="form.name" />
    </el-form-item>
    <el-form-item prop="description" label="描述">
      <el-input v-model="form.description" />
    </el-form-item>
    <el-form-item prop="categoryId" label="资源分类">
      <el-select v-model="form.categoryId">
        <el-option
          v-for="item of options"
          :label="item.name"
          :value="item.id"
          :key="item.id"
        />
      </el-select>
    </el-form-item>
    <el-form-item prop="url" label="资源路径">
      <el-input v-model="form.url" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submit">提交</el-button>
    </el-form-item>
  </el-form>
</template>
<script lang="ts">
import { getAllCategory, getResource, createOrEdit } from '@/services/resource'
import { wrapAsyncWithLoading } from '@/utils/helper'
import { ElForm } from 'element-ui/types/form'
import Vue from 'vue'
export default Vue.extend({
  name: 'FormAddOrEditResource',
  props: ['id'],
  data () {
    return {
      loading: false,
      form: {
        name: 'test_lnw_r_',
        description: '',
        url: ''
      },
      options: []
    }
  },
  created () {
    wrapAsyncWithLoading(this, 'loading', 'loadData')
    this.loadData()
  },
  methods: {
    async loadData () {
      await Promise.all([
        getAllCategory().then(({ data }) => {
          if (data.code === '000000') {
            this.options = data.data
            return
          }
          throw new Error('获取资源分类失败')
        }),
        this.id &&
          getResource(this.id).then(({ data }) => {
            if (data.code === '000000') {
              this.form = data.data
              return
            }
            throw new Error('获取资源失败')
          })
      ])
    },
    async submit () {
      try {
        await (this.$refs.form as ElForm).validate()
      } catch (error) {
        return
      }
      const { data } = await createOrEdit(this.form)
      if (data.code === '000000') {
        this.$emit('suc')
      }
    }
  }
})
</script>
